/*
 * @Author: wangtao
 * @Date: 2021-05-24 17:05:44
 * @LastEditors: 汪滔
 * @LastEditTime: 2021-07-19 14:02:45
 * @Description: 角色切换
 */

import React, { Component } from 'react';
import {
  StyleSheet,
  SafeAreaView,
  View,
  Text,
  TouchableOpacity,
  Image,
  NativeModules
} from 'react-native';
import { msg, BackImage, SyncStorage, cache } from '@/common';
import {
  px2dp,
  mainBgColorLightGray,
  fontColorSecDeepGray,
  screenWidth,
  isAndroid
} from '@/styles';
import { empty13, iconLogoutBlack } from '@/images';
import api from '@/api';
import RoleCard from './components/role-card';

const CookieManager = NativeModules.RNCookieManagerIOS;
export default class RoleSwitch extends Component {
  constructor(props) {
    super(props);
    this.state = {
      role: '',
    };
  }

  componentDidMount() {
    const Role = SyncStorage.getItem(cache.ROLE);
    this.setState({ role: Role });
  }

  render() {
    const { role } = this.state;
    return (
      <SafeAreaView style={styles.container}>
        <View style={styles.header}>
          {!!role && (
            <TouchableOpacity
              style={styles.headerLeft}
              activeOpacity={0.8}
              onPress={() => {
                msg.emit('router: back');
              }}
            >
              <BackImage />
            </TouchableOpacity>
          )}
          <TouchableOpacity
            style={styles.headerRight}
            activeOpacity={0.8}
            onPress={() => {
              this._loginout();
            }}
          >
            <Image source={iconLogoutBlack} resizeMode='contain' style={styles.logoutImg} />
            <Text style={styles.logoutText}>退出</Text>
          </TouchableOpacity>
        </View>

        <View style={styles.titleWrap}>
          <Text style={styles.title}>请选择您的身份</Text>
          <Text style={styles.subTitle}>选择后能为您提供相应的服务</Text>
        </View>

        <RoleCard type='driver' selectRole={this.selectRole} />
        <RoleCard type='car_owner' selectRole={this.selectRole} />

      </SafeAreaView>
    );
  }

  selectRole = (type) => {
    // const { type } = this.props;
    this.checkCertifi(type);
  }

  saveRole = (type) => {
    SyncStorage.setItem(cache.ROLE, type);
    // 司机：driver  车主：car_owner  货主：goods_owner
    if (type === 'driver') {
      msg.emit('router: reset', {
        routeName: 'DriverTab',
      });
    } else if (type === 'car_owner') {
      msg.emit('router: reset', {
        routeName: 'CarOwnerTab',
      });
    } else if (type === 'goods_owner') {
      msg.emit('router: reset', {
        routeName: 'GoodsOwnerTab',
      });
    }
  }

  checkCertifi = (type) => {
    // 是否完善身份认证
    api.user.getUserAuthInBusiness().then((res) => {
      if (res.success) {
        const sources = res.data;
        let filterArr = sources.filter((item) => {
          if (item.state === 2 && item.validateCode === 'REAL_NAME_AUTHENTICATION') {
            return true;
          }
          return false;
        });
        if (filterArr.length > 0) {
          msg.emit('app:messageBoxBig', {
            isVisible: true,
            text: '您还未完成实名认证,请前往认证!',
            okText: '去认证',
            okFn: () => {
              msg.emit('router: goToNext', {
                routeName: 'IdCardCertif',
                // code,
              });
            },
            imgSource: empty13
          });
        } else {
          this.saveRole(type);
        }
      } else {
        msg.emit('router: goToNext', {
          routeName: 'LoginView',
        });
      }
    });
  };

  toCarOwner = () => {
    msg.emit('router: goToNext', {
      routeName: 'CarOwnerMain',
    });
  }

  _loginout = () => {
    msg.emit('app:messageBox', {
      isVisible: true,
      text: '确定要退出当前账号吗？',
      okText: '确定',
      cancelText: '取消',
      okFn: () => {
        api.user
          .logout()
          .then((res) => {
            if (res.success) {
              if (__DEV__) {
                console.log('退出登录成功');
              }
              SyncStorage.removeItem(cache.USER_INFO);
              SyncStorage.removeItem(cache.ROLE);
              if (!isAndroid) {
                CookieManager.clearAll().then((res) => {
                  console.log('CookieManager.clearAll =>', res);
                });
              }
              msg.emit('router: reset', {
                routeName: 'LoginView',
              });
            } else {
              msg.emit('app:messageBox', {
                isVisible: true,
                title: '温馨提示',
                text: res.msg,
                okText: '确定',
              });
            }
          })
          .catch((res) => {
            if (__DEV__) {
              console.log(`退出异常：${res}`);
            }

            msg.emit('app:messageBox', {
              isVisible: true,
              title: '温馨提示',
              text: '退出异常',
              okText: '确定',
            });
          });
      },
      cancelFn: () => {
        console.log('🚀🚀🚀wimi======>>>cancelFn',);
      },
    });
  };
}
const styles = StyleSheet.create({
  container: {
    flex: 1,
    alignItems: 'center',
    backgroundColor: mainBgColorLightGray,
  },
  header: {
    width: screenWidth,
    height: px2dp(88),
    position: 'relative'
  },
  headerLeft: {
    width: px2dp(100),
    height: px2dp(88),
    justifyContent: 'center',
    alignItems: 'center',
    position: 'absolute',
    left: 0
  },
  titleWrap: {
    width: screenWidth,
    marginTop: px2dp(40),
    paddingHorizontal: px2dp(64),
  },
  title: {
    fontSize: px2dp(48),
    fontWeight: 'bold',
  },
  subTitle: {
    fontSize: px2dp(28),
    color: fontColorSecDeepGray,
    marginTop: px2dp(8),
    marginBottom: px2dp(24),
  },
  headerRight: {
    height: px2dp(88),
    justifyContent: 'center',
    alignItems: 'center',
    flexDirection: 'row',
    paddingHorizontal: px2dp(32),
    position: 'absolute',
    right: 0
  },
  logoutImg: {
    width: px2dp(36),
    height: px2dp(36),
  },
  logoutText: {
    fontSize: px2dp(28),
    marginLeft: px2dp(12)
  }
});
